/*
 *  ParsedXML.mm
 *  cactus-xml
 *
 *  Created by Yury Nikalayuk on 02.04.10.
 *  Copyright 2011 CactusSoft. All rights reserved.
 *
 */

#include "ParsedXML.h"

#import "DDXML.h"


ParsedXML::ParsedXML():
root(NULL)
{
}

ParsedXML::~ParsedXML()
{
}

bool ParsedXML::Prepare(const std::string &fileName)
{
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	
	NSString * strPath = [NSString stringWithUTF8String:fileName.c_str()];
	NSString *xmlString = [NSString stringWithContentsOfFile:strPath
						   encoding:NSUTF8StringEncoding error:NULL];
	if(![xmlString length])
	{
		[pool release];		
		return false;
	}
	
	
	NSError *theError = NULL;
	DDXMLDocument *theXMLDocument = [[DDXMLDocument alloc] initWithXMLString:xmlString options:0 error:&theError];
	root.reset( CreateNode([theXMLDocument rootElement]) );
	[theXMLDocument release];
	[pool release];
	return true;						   
}

const XMLNode & ParsedXML::Root() const
{
	return *(root.get());
}

XMLNode * ParsedXML::CreateNode(void *_source)
{
	DDXMLNode *source = (DDXMLNode *) _source;
	XMLNode *result = new XMLNode();
	result->name = [[source name] UTF8String];
	
	if([source kind] == DDXMLElementKind)
	{
		DDXMLElement *element = (DDXMLElement *) source;
		NSArray *attributes = [element attributes];
		for (DDXMLNode *attribute in attributes)
		{
			std::string key = [[attribute name] UTF8String];		
			std::string value = [[attribute stringValue] UTF8String];
			result->attributes[key] = XMLValue(value);
		}
	}
	
	for(DDXMLNode *child in [source children])
	{
		switch([child kind])
		{
			case DDXMLElementKind:
			{
				XMLNode *node = CreateNode(child);				
				result->childrenMap[node->name] = node;
				result->children.push_back(node);
			}
			break;
				
			case DDXMLTextKind:
			{
				result->value = XMLValue([[child stringValue] UTF8String]);
			}
			break;
		}
	}
	
	return result;
}
